<?php
define('ERR_LOGFILE', 'ERROR: Cannot open logfile. (maybe \'chmod 777 tmp\' ?)');
define('ERR_DB', 'ERROR: Cannot open database connection. (check your configs)');
define('ERR_DBQUERY', 'ERROR: Cannot query database');
define('ERR_GOOGLE', 'ERROR: Awh shucks, I searched and searched but found nothing. If you know you should have found somthing you may be blacklisted (lasts about 3-4 hrs).');
if(isset($_REQUEST['page'])) $prepage = $_REQUEST['page'];
else $prepage = 1;
if(isset($_REQUEST['num'])) $prenum = $_REQUEST['num'];
else $prenum = 1;
require_once 'config.php';
require_once 'snarf.lib.php';
$snarf = new snarfer;
#cache results
$statuslog = 'tmp/status.dat';
#

if(!isset($_POST['action'])){
	echo '<form action="signmeup.php" method="post">';
	echo '<h2 align="center">Here are your configs:</h2><br>';
	echo '<div style="width: 100%" id="db_config">';
	echo '<div align="center" style="width: 100%"><h3>MySQL config</h3></div>';
	echo '<div align="left" style="width: 60%; margin-left: 30%;">';
	foreach($mysqldb as $name => $value) {
		echo "<br><b><label style=\"width: 15%; float: left\">$name:</label></b> <label style=\"margin-left: 10%\">$value</label>";
	}
	echo "</div><br>";
	echo '<div style="width: 100%" id="search_config" name="search_config">';
	echo '<div align="center" style="width: 100%"><h3>Search config</h3></div>';
	echo '<div align="left" style="width: 60%; margin-left: 30%;" id="query_config" name="query_config">';
	echo '<br><label style="width: 15%; float: left"><b>Max num:</b></label>';
	echo '<input id="maxnum" name="maxnum" type="text"  value="' . $maxnum . '" style="margin-left: 10%; width: 5%" />';
	echo '<br><label style="width: 15%; float: left"><b>Max page:</b></label>';
	echo '<input id="maxpage" name="maxpage" type="text" value="' . $maxpage . '" style="margin-left: 10%; width: 5%" />';
	echo '<br><label style="width: 20%; float: left"><b>Term to search:</b></label>';
	echo "<textarea row=\"3\" col=\"50\" id=\"term\" name=\"term\" style=\"margin-left: 5%; width: 60%\"></textarea><br>";
	echo "</div><br>";
	echo '</div><br>';
	echo '<div style="width: 100%" id="run_options">';
	echo '<div align="center" style="width: 100%"><h3>Run Options</h3></div>';
	echo '<div align="left" style="width: 60%; margin-left: 30%;">';
	echo '<br><label style="width: 17%; float: left"><b>Select action:</b></label><select id="action" name="action" style="margin-left: 10%">';
	echo '<option value="start">Start</option>';
	echo '<option value="continue">Continue with the previous term</option>';
	echo '<option value="register">Register with the searched urls</option>';
	echo '<option value="export_registered">Export registered urls</option>';
	echo '<option value="export_unregistered">Export unregistered urls</option>';
	echo '<option value="capcha">Capcha</option>';
	echo '</select><br><br>';
	echo '<input type="submit" value="submit" style="width: 10%; margin-left: 30%;"/></div>';
	echo '</form>';
	exit;
}

// apply new db configuration
/*foreach($mysqldb as $name => $value) {
	$mysqldb[$name] = $_POST['db_'.$name];
}*/
$dbh = mysql_connect($mysqldb['host'], $mysqldb['user'], $mysqldb['pass']);
if(!$dbh) die("Line: " . __LINE__ ." ".  ERR_DB);
mysql_select_db($mysqldb['db'], $dbh);

// apply new search configuration
$maxnum = $_POST['maxnum'];
$maxpage = $_POST['maxpage'];

if($_POST['action'] == 'export_registered' || $_POST['action'] == 'export_unregistered') {
	if($_POST['action'] == 'export_registered')
		$sql='select * from signmeup where registered > 0';
	else
		$sql='select * from signmeup where registered = 0';
	$rsSearchResults = mysql_query($sql, $dbh) or die("Line: " . __LINE__ ." ". ERR_DBQUERY. mysql_error($dbh));
	$out = '';
	$fields = mysql_list_fields($mysqldb['db'],'signmeup',$dbh);
	$columns = mysql_num_fields($fields);
	// Put the name of all fields
	for ($i = 0; $i < $columns; $i++) {
		$l=mysql_field_name($fields, $i);
		$out .= '"'.$l.'",';
	}
	$out .="\n";

	// Add all values in the table
	while ($l = mysql_fetch_array($rsSearchResults)) {
		for ($i = 0; $i < $columns; $i++) {
			$out .='"'.$l["$i"].'",';
		}
		$out .="\n";
	}
	// Output to browser with appropriate mime type, you choose ;)
	header("Content-type: text/x-csv");
	if($_POST['action'] == 'export_registered'){
		header("Content-Disposition: attachment; filename=search_registered_results.csv");
	}else{
		header("Content-Disposition: attachment; filename=search_unregistered_results.csv");
	}

	echo $out;
	exit;
}

if($_POST['action'] == 'start'){
	$sh = fopen($statuslog, 'w+') or die("Line: " . __LINE__ ." ". ERR_LOGFILE);
	$suc=0;
	$total=0;
	$catyou=0;

	// truncate tables
	$sql = "TRUNCATE signmeup";
	$result = mysql_query($sql, $dbh);
	if (!$result) {
	    die("Line: " . __LINE__ ." ".ERR_DBQUERY);
	}
	$sql = "TRUNCATE capcha";
	$result = mysql_query($sql, $dbh);
	if (!$result) {
	    die("Line: " . __LINE__ ." ".ERR_DBQUERY);
	}
	$sql = "TRUNCATE status";
	$result = mysql_query($sql, $dbh);
	if (!$result) {
	    die("Line: " . __LINE__ ." ".ERR_DBQUERY);
	}

	for($page = $prepage; $page <= $maxpage; $page++) {
		$data = $snarf->GetGoogleResults($_POST['term'],$page,$maxnum);
		if(!$data) die("Line: " . __LINE__ ." ". ERR_GOOGLE);
		$num=0;
		foreach($data as $key => $target) {
			$num++;
			//if($num == $prenum) next;
			$url = $target['Url'];
			//preg_match('(?:http://)?([^/]', $url, $matches);
			preg_match('/[^.]+\.[^.]+\/+/', $url, $matches);
			if(preg_match('/http/', $matches[0]))
				$url = "{$matches[0]}";
			else $url = "http://{$matches[0]}";
			if(preg_match('/http/', $matches[0]))
				$host = "{$matches[0]}";
			else $host = "http://{$matches[0]}";
			/*$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $query['post']);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			$regpage = curl_exec($ch);
			curl_close($ch);*/
			$status = "$num-$page";
			ftruncate($sh,0);
			fwrite($sh,$status);
		//	echo $regpage;
		//	exit;

			// we get domain name
			$urlh=parse_url($url);
			$urlh=$urlh['host'];
			if(!mysql_num_rows(mysql_query("SELECT url FROM `signmeup` WHERE LOCATE('//{$urlh}/',url) LIMIT 1"))){
					$sql = sprintf("INSERT INTO signmeup(url,googlerank,registered) VALUES('%s', '%s', %d);", $host, $target['Rank'], 0);
					mysql_query($sql, $dbh) || die("Line: " . __LINE__ ." ".ERR_DBQUERY);
					$total ++;
			}
			// update total
			if(!mysql_num_rows(mysql_query("SELECT * FROM status")))
				$sql= sprintf("INSERT INTO status(id, total, term) VALUES(1, %d, '%s')", $total, mysql_escape_string($_POST['term']));
			else
				$sql = sprintf("UPDATE status SET total=%d WHERE id=1;", $total);
				mysql_query($sql, $dbh) || die("Line: " . __LINE__ ." ". ERR_DBQUERY . " " . mysql_error($dbh));
		}
		sleep(45);
	}
	echo "DONE!<br>Total: $total";
	echo "<br><a href=\"javascript:history.go(-1);\">Back</a></div>";
	fclose($sh);
}

if($_POST['action'] == 'continue'){
	$sh = fopen($statuslog, 'w+') or die("Line: " . __LINE__ ." ". ERR_LOGFILE);
	$total=0;
	$sql='select * from status;';
	$rsSearchResults = mysql_query($sql, $dbh) or die("Line: " . __LINE__ ." ". mysql_error());
	while ($l = mysql_fetch_array($rsSearchResults)) {
		$prev_total = $l["1"];
		$prev_catyou = $l["2"];
		$prev_term= $l["3"];
	}
	if($prev_total == 0){
		echo "<div><b>It's the first time you run the script, so you should choose 'start' instead of 'continue'</b>";
		echo "<br><a href=\"javascript:history.go(-1);\">Back</a></div>";
		mysql_close($dbh);
		exit;
	}
	/*if($prev_query_id != $_POST['query_option']){
		echo "<div><b>You selected this query number: $prev_query_id, so you should choose 'start' with your current selected query</b>";
		echo "<br><a href=\"javascript:history.go(-1);\">Back</a></div>";
		mysql_close($dbh);
		exit;
	}*/
	$total = $prev_total;
	$prepage = floor($total/$maxnum);
	for($page = $prepage; $page <= $prepage + $maxpage; $page++) {
		$data = $snarf->GetGoogleResults($prev_term,$page,$maxnum);
		if(!$data) die("Line: " . __LINE__ ." ". ERR_GOOGLE);
		$num=0;
		foreach($data as $key => $target) {
			$num++;
			if(($num + ($page * $maxnum) )< $prev_total){
		//		echo ($num + $page *$maxnum);
				 continue;
			}
			//if($num == $prenum) next;
			$url = $target['Url'];
			//preg_match('(?:http://)?([^/]', $url, $matches);
			preg_match('/[^.]+\.[^.]+\/+/', $url, $matches);
			if(preg_match('/http/', $matches[0]))
				$url = "{$matches[0]}";
			else $url = "http://{$matches[0]}";
			if(preg_match('/http/', $matches[0]))
				$host = "{$matches[0]}";
			else $host = "http://{$matches[0]}";
			$status = "$num-$page";
			ftruncate($sh,0);
			fwrite($sh,$status);
			// we get domain name
			$urlh=parse_url($url);
			$urlh=$urlh['host'];
			if(!mysql_num_rows(mysql_query("SELECT url FROM `signmeup` WHERE LOCATE('//{$urlh}/',url) LIMIT 1"))){
				$sql = sprintf("INSERT INTO signmeup(url, googlerank, registered) VALUES('%s', '%s', %d);", $host, $target['Rank'], 0);
				mysql_query($sql, $dbh) || die(ERR_DBQUERY);
				//update total
				$total++;
				if(!mysql_num_rows(mysql_query("SELECT * FROM status")))
					$sql= sprintf("INSERT INTO status(id, total, term) VALUES(1, %d, '%s')", $total, $_POST['term']);
				else
					$sql = sprintf("UPDATE status SET total=%d, term='%s' WHERE id=1;", $total, $_POST['term']);
				mysql_query($sql, $dbh) || die("Line: " . __LINE__ ." ". ERR_DBQUERY . ": " . mysql_error($dbh) );
			}
		}
		sleep(45);
	}
	echo "DONE!<br>Total: $total";
	echo "<br><a href=\"javascript:history.go(-1);\">Back</a></div>";
	fclose($sh);
}
if($_POST['action'] == 'capcha'){
	require_once('capcha.php');
}

if($_POST['action'] == 'register'){
	header('location: register.php');
}
mysql_close($dbh);
//echo $snarf->get_page_rank($_GET['url']);

?>
